package servlet;

import dao.MessageDAO;
import javabean.Message;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "MessageServlet", value = "/message")
public class MessageServlet extends HttpServlet {
    private MessageDAO messageDao = new MessageDAO();
    private static final int PAGE_SIZE = 5;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");

        try {
            if ("add".equals(action)) {
                addNewMessage(request);
            }
            else if ("delete".equals(action)) {
                deleteMessage(request);
            }
            else if ("reply".equals(action)) {
                addReply(request);
            }
            else if ("login".equals(action)) {
                adminLogin(request, response);
                return; // 避免重定向两次
            }
        } catch (SQLException e) {
            throw new ServletException("数据库操作失败", e);
        }

        response.sendRedirect("index.jsp");
    }

    private void addNewMessage(HttpServletRequest request) throws SQLException {
        Message msg = new Message();
        msg.setName(request.getParameter("name"));
        msg.setTime(new java.util.Date());
        msg.setQq(request.getParameter("qq"));
        msg.setEmail(request.getParameter("email"));
        msg.setContent(request.getParameter("content"));
        messageDao.addMessage(msg);
    }

    private void deleteMessage(HttpServletRequest request) throws SQLException {
        int id = Integer.parseInt(request.getParameter("id"));
        messageDao.deleteMessage(id);
    }

    private void addReply(HttpServletRequest request) throws SQLException {
        int id = Integer.parseInt(request.getParameter("id"));
        String reply = request.getParameter("reply");
        messageDao.addReply(id, reply);
    }

    private void adminLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 简单验证（实际应使用数据库验证）
        if ("admin".equals(username) && "admin123".equals(password)) {
            request.getSession().setAttribute("admin", true);
            response.sendRedirect("index.jsp");
        } else {
            request.setAttribute("error", "用户名或密码错误");
            doGet(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            int page = 1;
            if (request.getParameter("page") != null) {
                page = Integer.parseInt(request.getParameter("page"));
            }

            List<Message> messages = messageDao.getAllMessages(page, PAGE_SIZE);
            int totalMessages = messageDao.getTotalMessages();
            int totalPages = (int) Math.ceil((double) totalMessages / PAGE_SIZE);

            request.setAttribute("messages", messages);
            request.setAttribute("currentPage", page);
            request.setAttribute("totalPages", totalPages);
        } catch (SQLException e) {
            throw new ServletException("数据库查询失败", e);
        }

        request.getRequestDispatcher("index.jsp").forward(request, response);
    }
}